import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo } from '@/api/user'

const state = {
  token: getToken(),
  userId: null,
  userInfo: null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // 获取用户信息
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo(state.userId).then(response => {
        const { data } = response
        commit('SET_USER_INFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 登出
  logout({ commit }) {
    commit('SET_TOKEN', '')
    commit('SET_USER_ID', null)
    commit('SET_USER_INFO', null)
    removeToken()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
